<template>
  <div class="practice-list-page">
    <!-- 标题栏 -->
    <div class="navbar">
      <div class="nav-back" @click="$router.go(-1)">
        <i class="fas fa-chevron-left"></i>
      </div>
      <div class="nav-title">分配练习任务</div>
      <div></div>
    </div>

    <!-- 内容区域 -->
    <div class="content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        <div class="spinner"></div>
        <span>加载中...</span>
      </div>

      <!-- 空状态 -->
      <div v-else-if="practiceList.length === 0" class="empty">
        <div class="empty-icon">📝</div>
        <p>暂无练习数据</p>
      </div>

      <!-- 列表内容 -->
      <div v-else class="practice-list">
        <div class="list-header">
          <h2>选择练习任务</h2>
          <span class="selected-count"
            >已选择 {{ selectedPractices.length }} 个</span
          >
        </div>

        <div
          v-for="item in practiceList"
          :key="item.id"
          class="practice-item"
          :class="{ selected: selectedPractices.includes(item.id) }"
        >
          <div class="item-header">
            <div class="item-left">
              <label class="checkbox-container">
                <input
                  type="checkbox"
                  v-model="selectedPractices"
                  :value="item.id"
                  class="practice-checkbox"
                />
                <span class="checkmark"></span>
              </label>
              <div class="title-section">
                <h3 class="item-title">{{ item.title }}</h3>
                <span class="item-tag">{{ item.tag }}</span>
              </div>
            </div>
            <div class="item-duration">
              <span class="duration-icon">⏱</span>
              {{ item.minute }}分钟
            </div>
          </div>

          <div class="item-info">{{ item.info }}</div>

          <div class="item-footer">
            <span class="item-type">
              <span class="type-icon">{{ getTypeIcon(item.type) }}</span>
              {{ getTypeText(item.type) }}
            </span>
          </div>

          <!-- 时间选择区域 -->
          <div
            v-if="selectedPractices.includes(item.id)"
            class="time-selection"
          >
            <div class="time-input-group">
              <div class="time-label">
                <span class="time-icon">📅</span>
                开始时间
              </div>
              <input
                type="datetime-local"
                v-model="timeRanges[item.id].startTime"
                class="time-input"
                :min="minDateTime"
              />
            </div>
            <div class="time-input-group">
              <div class="time-label">
                <span class="time-icon">🎯</span>
                结束时间
              </div>
              <input
                type="datetime-local"
                v-model="timeRanges[item.id].endTime"
                class="time-input"
                :min="timeRanges[item.id].startTime || minDateTime"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div
        class="submit-section"
        v-if="practiceList.length > 0 && selectedPractices.length > 0"
      >
        <button
          class="submit-btn"
          @click="handleAssignPractice"
          :disabled="isSubmitting"
          :class="{ loading: isSubmitting }"
        >
          <span v-if="!isSubmitting">
            🚀 分配选中的 {{ selectedPractices.length }} 个练习
          </span>
          <span v-else>
            <div class="btn-spinner"></div>
            提交中...
          </span>
        </button>
      </div>
    </div>

    <!-- 自定义提示消息 -->
    <div v-if="message.show" class="custom-message" :class="message.type">
      <span class="message-icon">{{
        message.type === "success" ? "✅" : "❌"
      }}</span>
      {{ message.text }}
    </div>
  </div>
</template>

<script>
import { getPracticeList, assignPractice } from "../../api/case";

export default {
  name: "PracticeList",
  data() {
    return {
      practiceList: [],
      loading: false,
      isSubmitting: false,
      selectedPractices: [],
      timeRanges: {},
      pageParams: {
        teacherId: "",
        mobile: "",
        cusId: "",
      },
      message: {
        show: false,
        text: "",
        type: "success",
      },
    };
  },
  computed: {
    minDateTime() {
      const now = new Date();
      return now.toISOString().slice(0, 16);
    },
  },
  methods: {
    // 显示消息提示
    showMessage(text, type = "success") {
      this.message = {
        show: true,
        text,
        type,
      };
      setTimeout(() => {
        this.message.show = false;
      }, 3000);
    },

    // 获取练习列表
    getPracticeList() {
      this.loading = true;
      let data = { appointId: this.appointId };
      getPracticeList(data)
        .then((res) => {
          if (res.code === 200) {
            this.practiceList = res.data || [];
            this.initTimeRanges();
          } else {
            console.error("获取数据失败:", res.message);
            this.showMessage(res.message || "获取数据失败", "error");
          }
        })
        .catch((error) => {
          console.error("接口请求失败:", error);
          this.showMessage("网络请求失败", "error");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 初始化时间范围对象
    initTimeRanges() {
      const ranges = {};
      this.practiceList.forEach((item) => {
        const now = new Date();
        const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000);

        ranges[item.id] = {
          startTime: now.toISOString().slice(0, 16),
          endTime: tomorrow.toISOString().slice(0, 16),
        };
      });
      this.timeRanges = ranges;
    },

    // 解析URL参数
    parseUrlParams() {
      try {
        // 从路由query中获取参数
        const query = this.$route.query;
        if (query.caseItem) {
          const caseItem = JSON.parse(query.caseItem);
          console.log("解析的参数:", caseItem);
          this.pageParams.teacherId = localStorage.getItem("teacherId") || "";
          this.pageParams.mobile = caseItem.mobile || "";
          this.pageParams.cusId = caseItem.cusId || "";
          this.appointId = caseItem.id;
        }

        // 如果没有找到参数，尝试从其他方式获取
        if (!this.pageParams.teacherId) {
          console.warn("未找到必要的页面参数");
        }
      } catch (error) {
        console.error("解析URL参数失败:", error);
        this.showMessage("参数解析失败", "error");
      }
    },

    // 处理分配练习
    handleAssignPractice() {
      // 验证必填参数
      if (
        !this.pageParams.teacherId ||
        !this.pageParams.mobile ||
        !this.pageParams.cusId
      ) {
        this.showMessage("缺少必要的用户参数", "error");
        return;
      }

      if (this.selectedPractices.length === 0) {
        this.showMessage("请至少选择一个练习", "error");
        return;
      }

      // 验证时间
      for (const practiceId of this.selectedPractices) {
        const timeRange = this.timeRanges[practiceId];
        if (!timeRange.startTime || !timeRange.endTime) {
          this.showMessage("请为所有选中的练习设置开始和结束时间", "error");
          return;
        }

        const startTime = new Date(timeRange.startTime);
        const endTime = new Date(timeRange.endTime);

        if (endTime <= startTime) {
          this.showMessage("结束时间必须晚于开始时间", "error");
          return;
        }
      }

      // 构建请求数据
      const requestData = {
        teacherId: this.pageParams.teacherId,
        appointId: this.appointId,

        phone: this.pageParams.mobile,
        cusId: this.pageParams.cusId,
        practiceList: this.selectedPractices.map((practiceId) => ({
          practiceid: practiceId,
          starttime: this.formatDateTime(this.timeRanges[practiceId].startTime),
          endtime: this.formatDateTime(this.timeRanges[practiceId].endTime),
        })),
      };

      console.log("提交数据:", requestData);
      this.submitAssignPractice(requestData);
    },

    // 提交分配练习
    submitAssignPractice(requestData) {
      this.isSubmitting = true;

      assignPractice(requestData)
        .then((res) => {
          if (res.code === 200) {
            this.showMessage("练习分配成功！");
            setTimeout(() => {
              this.$router.go(-1);
            }, 1500);
          } else {
            console.error("分配失败:", res.message);
            this.showMessage(res.message || "分配失败", "error");
          }
        })
        .catch((error) => {
          console.error("分配请求失败:", error);
          this.showMessage("网络请求失败", "error");
        })
        .finally(() => {
          this.isSubmitting = false;
        });
    },

    // 格式化日期时间
    formatDateTime(dateTimeString) {
      if (!dateTimeString) return "";
      const date = new Date(dateTimeString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 根据类型值获取类型文本
    getTypeText(type) {
      const typeMap = {
        1: "基础练习",
        2: "进阶练习",
        3: "专项练习",
      };
      return typeMap[type] || `类型${type}`;
    },

    // 获取类型图标
    getTypeIcon(type) {
      const iconMap = {
        1: "📚",
        2: "⚡",
        3: "🎯",
      };
      return iconMap[type] || "📄";
    },
  },
  mounted() {
    this.parseUrlParams();
    this.getPracticeList();
  },
};
</script>

<style scoped>
.practice-list-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #c8d1fc 0%, #c5bbfd 100%);
  padding-bottom: 100px;
  position: relative;
}

/* 导航栏样式 */
.navbar {
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  z-index: 1000;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.nav-back {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #333;
  font-size: 18px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.nav-back:hover {
  background: #e0e0e0;
}

.nav-title {
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

/* 内容区域样式 */
.content {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

/* 加载状态 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: white;
  font-size: 18px;
  gap: 20px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-left: 4px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 空状态 */
.empty {
  text-align: center;
  padding: 80px 20px;
  color: white;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.empty p {
  font-size: 18px;
  opacity: 0.9;
}

/* 列表头部 */
.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding: 0 10px;
}

.list-header h2 {
  color: white;
  font-size: 24px;
  font-weight: 700;
  margin: 0;
}

.selected-count {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 600;
  backdrop-filter: blur(10px);
}

/* 练习列表样式 */
.practice-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.practice-item {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.practice-item::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.practice-item.selected::before {
  transform: scaleX(1);
}

.practice-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.item-left {
  display: flex;
  align-items: flex-start;
  flex: 1;
  gap: 12px;
}

/* 自定义复选框 */
.checkbox-container {
  display: block;
  position: relative;
  cursor: pointer;
  margin-top: 4px;
}

.practice-checkbox {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

.checkmark {
  width: 22px;
  height: 22px;
  background: #f8f9fa;
  border: 2px solid #e2e8f0;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.practice-checkbox:checked + .checkmark {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-color: #667eea;
}

.checkmark:after {
  content: "✓";
  color: white;
  font-size: 14px;
  font-weight: bold;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.practice-checkbox:checked + .checkmark:after {
  opacity: 1;
}

.title-section {
  flex: 1;
}

.item-title {
  margin: 0 0 6px 0;
  font-size: 17px;
  color: #2d3748;
  font-weight: 600;
  line-height: 1.4;
}

.item-tag {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  display: inline-block;
}

.item-duration {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #718096;
  font-size: 14px;
  font-weight: 600;
}

.duration-icon {
  font-size: 16px;
}

.item-info {
  color: #718096;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-footer {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #718096;
}

.item-type {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
}

.type-icon {
  font-size: 16px;
}

/* 时间选择区域 */
.time-selection {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e2e8f0;
  animation: slideDown 0.3s ease;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.time-input-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}

.time-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #4a5568;
  font-weight: 600;
}

.time-icon {
  font-size: 16px;
}

.time-input {
  padding: 12px 16px;
  border: 2px solid #e2e8f0;
  border-radius: 10px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: white;
}

.time-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 提交按钮区域 */
.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
}

.submit-btn {
  width: 100%;
  padding: 16px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.submit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.submit-btn.loading {
  opacity: 0.8;
}

.btn-spinner {
  width: 18px;
  height: 18px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-left: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

/* 自定义消息提示 */
.custom-message {
  position: fixed;
  top: 90px;
  left: 50%;
  transform: translateX(-50%);
  padding: 16px 24px;
  border-radius: 12px;
  font-weight: 600;
  z-index: 2000;
  display: flex;
  align-items: center;
  gap: 10px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  animation: slideIn 0.3s ease;
  max-width: 90%;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

.custom-message.success {
  background: linear-gradient(135deg, #48bb78, #38a169);
  color: white;
}

.custom-message.error {
  background: linear-gradient(135deg, #f56565, #e53e3e);
  color: white;
}

.message-icon {
  font-size: 18px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content {
    padding: 15px;
  }

  .practice-item {
    padding: 16px;
  }

  .item-header {
    flex-direction: column;
    gap: 12px;
  }

  .item-duration {
    align-self: flex-start;
  }

  .list-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
}
</style>
